<template>
  <view>
    <view class="nav">
      <text></text>
      <text class="title">{{ title }}</text>
      <text class="ble" @tap="goBle">{{
        title ? "断开连接" : "蓝牙连接"
      }}</text>
    </view>
    <uni-section title="发送数据:" type="line" class="scroll">
      <scroll-view scroll-y class="box">
        <view class="item">
          <view v-for="(item, index) in sendData" :key="index">
            <text>{{ item }}</text>
          </view>
        </view>
      </scroll-view>
    </uni-section>
    <uni-section title="接收数据:" type="line" class="scroll">
      <scroll-view scroll-y class="box">
        <view class="item">
          <view v-for="(item, index) in acceptData" :key="index">
            <text>{{ item }}</text>
          </view>
        </view>
      </scroll-view>
    </uni-section>
    <view class="empty"
      ><button type="primary" size="mini" @tap="clearData">清空</button></view
    >
    <uni-section>
      <uni-collapse accordion v-model="accordionVal">
        <uni-collapse-item title="查询指令">
          <view class="content">
            <text
              class="text"
              v-for="(item, index) in queryCommand"
              :key="index"
              @click="queryCTPL(item, index)"
              :class="{ active: queryIndex === index }"
              >{{ item }}</text
            >
          </view>
        </uni-collapse-item>
        <uni-collapse-item title="设置指令">
          <view class="content">
            <text
              class="text"
              v-for="(item, index) in settingCommand"
              :key="index"
              @click="setCTPL(index)"
              :class="{ active: settingIndex === index }"
              >{{ item }}</text
            >
          </view>
        </uni-collapse-item>
        <uni-collapse-item title="打印指令">
          <view class="content">
            <text
              class="text"
              v-for="(item, index) in printCommand"
              :key="index"
              @click="printCTPL(index)"
              :class="{ active: printIndex === index }"
              >{{ item }}</text
            >
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </uni-section>
    <canvas
      canvas-id="canvas"
      id="canvas"
      style="width: 400px; height: 400px"
    ></canvas>
    <!-- 设置模式 -->
    <uni-popup ref="dialog" type="center" :animation="true">
      <uni-popup-dialog
        mode="base"
        :before-close="true"
        @confirm="confirm"
        @close="close"
      >
        <view class="popup-cont">
          <view class="popup-list">
            <input
              type="number"
              v-model="printMode"
              placeholder="请输入参数0~3"
              v-if="settingIndex === 0"
            />
            <input
              type="number"
              v-model="paperType"
              placeholder="请输入参数0~2"
              v-if="settingIndex === 1"
            />
            <input
              type="number"
              v-model="memoryPrint"
              placeholder="请输入参数0~1"
              v-if="settingIndex === 2"
            />
            <input
              type="number"
              v-model="autoshutDown"
              placeholder="请输入参数1~60min"
              v-if="settingIndex === 3"
            />
            <input
              type="number"
              v-model="density"
              placeholder="请输入打印浓度1~15"
              v-if="settingIndex === 5"
            />
            <input
              type="number"
              v-model="printSpeed"
              placeholder="请输入打印速度1~6"
              v-if="settingIndex === 6"
            />
            <input
              type="number"
              v-model="printDirection"
              placeholder="请输入打印方向0或1"
              v-if="settingIndex === 8"
            />
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
    <!-- 打印模式 -->
    <uni-popup ref="dialog1" type="center" :animation="true">
      <uni-popup-dialog
        mode="base"
        :before-close="true"
        @confirm="confirm1"
        @close="close1"
      >
        <view class="popup-cont">
          <view class="popup-list">
            <input
              type="number"
              v-model="paperObj.width"
              placeholder="请输入宽度"
              v-if="printIndex === 0"
            />
            <input
              type="number"
              v-model="paperObj.height"
              placeholder="请输入高度"
              v-if="printIndex === 0"
            />
            <input
              type="number"
              v-model="lineObj.x"
              placeholder="请输入线条起始点x"
              v-if="printIndex === 1"
            />
            <input
              type="number"
              v-model="lineObj.y"
              placeholder="请输入线条起始点y"
              v-if="printIndex === 1"
            />
            <input
              type="number"
              v-model="lineObj.width"
              placeholder="请输入线条长度"
              v-if="printIndex === 1"
            />
            <input
              type="number"
              v-model="lineObj.height"
              placeholder="请输入线条高度"
              v-if="printIndex === 1"
            />
            <input
              type="number"
              v-model="textObj.x"
              placeholder="请输入文字起始点x"
              v-if="printIndex === 2"
            />
            <input
              type="number"
              v-model="textObj.y"
              placeholder="请输入文字起始点y"
              v-if="printIndex === 2"
            />
            <input
              type="number"
              v-model="textObj.rotation"
              placeholder="请输入旋转方向"
              v-if="printIndex === 2"
            />
            <input
              type="number"
              v-model="textObj.xRatio"
              placeholder="请输入x轴放大倍率"
              v-if="printIndex === 2"
            />
            <input
              type="number"
              v-model="textObj.yRatio"
              placeholder="请输入y轴放大倍率"
              v-if="printIndex === 2"
            />
            <input
              type="number"
              v-model="textObj.textAlignment"
              placeholder="请输入文字对齐"
              v-if="printIndex === 2"
            />
            <input
              type="text"
              v-model="textObj.text"
              placeholder="请输入要打印的文本内容"
              v-if="printIndex === 2"
            />
            <input
              type="number"
              v-model="barcodeObj.x"
              placeholder="请输入条码起始点x"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.y"
              placeholder="请输入条码起始点y"
              v-if="printIndex === 3"
            />
            <input
              v-model="barcodeObj.codeType"
              placeholder="请输入条码类型"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.height"
              placeholder="请输入条码高度"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.displayBarCode"
              placeholder="条码事发后展示码文以及码文对齐方式"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.rotation"
              placeholder="请输入旋转角度"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.narrow"
              placeholder="请输入窄比例因子"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.wide"
              placeholder="请输入宽比例因子"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="barcodeObj.alignment"
              placeholder="请输入条码对齐方式"
              v-if="printIndex === 3"
            />
            <input
              type="text"
              v-model="barcodeObj.content"
              placeholder="请输入条码内容"
              v-if="printIndex === 3"
            />
            <input
              type="number"
              v-model="qrcodeObj.x"
              placeholder="请输入二维码起始点x"
              v-if="printIndex === 4"
            />
            <input
              type="number"
              v-model="qrcodeObj.y"
              placeholder="请输入二维码起始点y"
              v-if="printIndex === 4"
            />
            <input
              v-model="qrcodeObj.eccLevel"
              placeholder="请输入纠错等级"
              v-if="printIndex === 4"
            />
            <input
              type="number"
              v-model="qrcodeObj.cellWidth"
              placeholder="请输入二维码格子宽度"
              v-if="printIndex === 4"
            />
            <input
              v-model="qrcodeObj.encodeMode"
              placeholder="二维码编码模式"
              v-if="printIndex === 4"
            />
            <input
              type="number"
              v-model="qrcodeObj.rotation"
              placeholder="请输入旋转角度"
              v-if="printIndex === 4"
            />
            <input
              v-model="qrcodeObj.codeMode"
              placeholder="请输入二维码码制"
              v-if="printIndex === 4"
            />
            <input
              v-model="qrcodeObj.mask"
              placeholder="请输入蒙版等级"
              v-if="printIndex === 4"
            />
            <input
              type="text"
              v-model="qrcodeObj.content"
              placeholder="请输入二维码内容"
              v-if="printIndex === 4"
            />
            <input
              type="number"
              v-model="bitMapObj.x"
              placeholder="请输入图片起始点x"
              v-if="printIndex === 5"
            />
            <input
              type="number"
              v-model="bitMapObj.y"
              placeholder="请输入图片起始点y"
              v-if="printIndex === 5"
            />
            <input
              type="number"
              v-model="bitMapObj.width"
              placeholder="请输入图片宽度"
              v-if="printIndex === 5"
            />
            <input
              type="number"
              v-model="bitMapObj.height"
              placeholder="请输入图片高度"
              v-if="printIndex === 5"
            />
            <input
              type="number"
              v-model="compressBitMapObj.x"
              placeholder="请输入图片起始点x"
              v-if="printIndex === 6"
            />
            <input
              type="number"
              v-model="compressBitMapObj.y"
              placeholder="请输入图片起始点y"
              v-if="printIndex === 6"
            />
            <input
              type="number"
              v-model="compressBitMapObj.width"
              placeholder="请输入图片宽度"
              v-if="printIndex === 6"
            />
            <input
              type="number"
              v-model="compressBitMapObj.height"
              placeholder="请输入图片高度"
              v-if="printIndex === 6"
            />
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>
<script>
import CTPL from "../../web-CTPL-SDK/ctpl.js";
// const CTPL = require("../../web-CTPL-SDK/ctpl.js")
export default {
  data() {
    return {
      accordionVal: "2",
      sendData: [], //发送数据
      acceptData: [], //接收数据
      queryCommand: [
        "查询硬件配置（合并）",
        "查询打印机型号",
        "查询支持压缩算法",
        "查询固件信息（合并）",
        "查询纸张类型",
        "查询记忆打印状态",
        "查询打印浓度",
        "查询打印速度",
        "查询自动关机（分钟）",
        "查询展示参数（合并）",
        "查询硬件版本号",
        "查询当前电量",
        "查询打印模式",
      ], //查询指令
      queryIndex: -1,
      settingCommand: [
        "设置打印模式",
        "设置纸张类型",
        "设置记忆打印",
        "设置自动关机（分钟）",
        "恢复出厂设置",
        "设置打印浓度",
        "设置打印速度",
        "设置标签的打印份数",
        "设置打印方向",
      ], //设置指令
      settingIndex: -1,
      printCommand: [
        "设置纸张的宽度跟高度",
        "绘制线条",
        "绘制文字",
        "绘制条码",
        "绘制二维码",
        "绘制图片",
        "绘制压缩图片",
        "执行打印",
      ], //打印指令
      printMode: 0, //标签模式/间隙纸，标签模式/连续纸，标签模式/黑标纸，票据模式/连续纸
      paperType: 0, //设置纸张类型
      memoryPrint: 0, //记忆打印
      autoshutDown: 1, //自动睡眠
      density: 1, //打印浓度
      printSpeed: 1, //打印速度
      printDirection: 0, //打印方向
      printIndex: -1, //打印index
      //打印图元
      pelData: [],
      //新的图片高度
      newHeight: "",
      paperObj: {
        width: "45",
        height: "45",
      },
      lineObj: {
        type: "line",
        x: 0,
        y: 0,
        width: 10,
        height: 2,
      },
      textObj: {
        type: "text",
        x: 5,
        y: 5,
        rotation: 0,
        xRatio: 0,
        yRatio: 0,
        textAlignment:0,
        text: "编辑文本123456",
      },
      barcodeObj: {
        type: "barcode",
        x: 0,
        y: 0,
        codeType: 128,
        height: 30,
        displayBarCode: 1,
        rotation: 0,
        narrow: 5,
        wide: 5,
        alignment: 0,
        content: 1234567890,
      },
      qrcodeObj: {
        type: "qrcode",
        x: 0,
        y: 0,
        eccLevel: "H",
        cellWidth: 5,
        encodeMode: "M",
        rotation: 0,
        codeMode: "M1",
        mask: "S7",
        content: 1234567890,
      },
      bitMapObj: {
        type: "bitmap",
        x: 0,
        y: 0,
        width: 0,
        height: 0,
      },
      compressBitMapObj: {
        type: "compressbitmap",
        x: 0,
        y: 0,
        width: 0,
        height: 0,
      },
      imageData: "",
      imagePath: "/static/images/tupian.png",
      title: "",
      //图片数据
      imageRes: {},
    };
  },
  onLoad(options) {
    this.title = options.blename
      ? `${options.blename} ${options.deviceId}`
      : "";
  },
  methods: {
    //连接蓝牙
    goBle() {
      if (this.title) {
        CTPL.disconnect();
        this.title = "";
      } else {
        uni.navigateTo({
          url: "connectble",
        });
      }
    },
    //查询指令
    async queryCTPL(item, index) {
      this.queryIndex = index;
      if (index === 0) {
        //查询硬件配置（合并）
        const res = await CTPL.queryHardwareConfig();
        this.sendData.push(item);
        this.acceptData.push(`硬件配置信息：${JSON.stringify(res)}`);
      } else if (index === 1) {
        //查询打印机型号
        const res = await CTPL.queryHardwareModel();
        this.sendData.push(item);
        this.acceptData.push(`打印机型号：${res}`);
      } else if (index === 2) {
        // 查询支持压缩算法
        const res = await CTPL.queryCompressPrint();
        this.sendData.push(item);
        this.acceptData.push(`支持压缩算法：${res}`);
      } else if (index === 3) {
        // 查询固件信息（合并）
        const res = await CTPL.queryFirmwareInfo();
        this.sendData.push(item);
        this.acceptData.push(`固件信息：${JSON.stringify(res)}`);
      } else if (index === 4) {
        // 查询纸张类型
        const res = await CTPL.queryPaperType();
        this.sendData.push(item);
        this.acceptData.push(`纸张类型：${res}`);
      } else if (index === 5) {
        // 查询记忆打印状态
        const res = await CTPL.queryMemoryPrint();
        this.sendData.push(item);
        this.acceptData.push(`记忆打印状态：${res}`);
      } else if (index === 6) {
        // 查询打印浓度
        const res = await CTPL.queryDensity();
        this.sendData.push(item);
        this.acceptData.push(`打印浓度：${res}`);
      } else if (index === 7) {
        // 查询打印速度
        const res = await CTPL.querySpeed();
        this.sendData.push(item);
        this.acceptData.push(`打印速度：${res}`);
      } else if (index === 8) {
        // 查询自动关机（分钟）
        const res = await CTPL.queryAutoShutDown();
        this.sendData.push(item);
        this.acceptData.push(`自动关机（分钟）：${res}`);
      } else if (index === 9) {
        // 查询展示参数（合并）
        const res = await CTPL.queryDisplayInfo();
        this.sendData.push(item);
        this.acceptData.push(`展示参数（合并）：${JSON.stringify(res)}`);
      } else if (index === 10) {
        // 查询硬件版本号
        const res = await CTPL.queryHardwareVersion();
        this.sendData.push(item);
        this.acceptData.push(`硬件版本号：${res}`);
      } else if (index === 11) {
        // 查询当前电量
        const res = await CTPL.queryBattery();
        this.sendData.push(item);
        this.acceptData.push(`当前电量：${res}`);
      } else if (index === 12) {
        // 查询打印模式
        const res = await CTPL.queryPrintMode();
        this.sendData.push(item);
        this.acceptData.push(`打印模式：${res}`);
      }
    },
    //设置指令
    async setCTPL(index) {
      this.settingIndex = index;
      if (index === 4) {
        CTPL.resetFirmware();
      } else if (index === 7) {
      } else {
        this.$refs.dialog.open();
      }
    },
    //打印指令
    printCTPL(index) {
      this.printIndex = index;
      if (this.printIndex === 7) {
        this.print();
      } else {
        this.$refs.dialog1.open();
      }
    },
    close() {
      this.$refs.dialog.close();
    },
    close1() {
      this.$refs.dialog1.close();
    },
    async confirm() {
      if (this.settingIndex === 0) {
        //设置打印模式
        CTPL.setPrintMode(this.printMode);
        this.sendData.push(`设置打印模式：${this.printMode}`);
      } else if (this.settingIndex === 1) {
        //设置纸张类型
        CTPL.setPaperType(this.paperType);
        this.sendData.push(`设置纸张类型：${this.paperType}`);
      } else if (this.settingIndex === 2) {
        // 设置记忆打印
        CTPL.setMemoryPrint(this.memoryPrint);
        this.sendData.push(`设置记忆打印：${this.memoryPrint}`);
      } else if (this.settingIndex === 3) {
        // 设置自动关机（分钟）
        CTPL.setAutoShutdown(this.autoshutDown);
        this.sendData.push(`设置自动关机：${this.autoshutDown}`);
      } else if (this.settingIndex === 5) {
        // 设置打印浓度
        CTPL.setDensity(this.density);
        this.sendData.push(`设置打印浓度：${this.density}`);
      } else if (this.settingIndex === 6) {
        // 设置打印速度
        CTPL.setSpeed(this.printSpeed);
        this.sendData.push(`设置打印速度：${this.printSpeed}`);
      } else if (this.settingIndex === 8) {
        // 设置打印方向
        CTPL.setDirection(this.printDirection);
        this.sendData.push(`设置打印方向和镜像：${this.printDirection}`);
      }
      this.$refs.dialog.close();
    },
    confirm1() {
      if (this.printIndex === 0) {
        //设置纸张的宽度跟高度
        this.sendData.push(
          `设置纸张的宽度跟高度：${this.paperObj.width},${this.paperObj.height}`
        );
      } else if (this.printIndex === 1) {
        //绘制线条
        this.pelData.push(this.lineObj);
        this.sendData.push(
          `绘制线条：${this.lineObj.x},${this.lineObj.y},${this.lineObj.width},${this.lineObj.height}`
        );
      } else if (this.printIndex === 2) {
        // 绘制文字
        this.pelData.push(this.textObj);
        this.sendData.push(
          `绘制文字：${this.textObj.x},${this.textObj.y},${this.textObj.rotation},${this.textObj.xRatio},${this.textObj.yRatio},${this.textObj.textAlignment},${this.textObj.text},`
        );
      } else if (this.printIndex === 3) {
        // 绘制条码
        this.pelData.push(this.barcodeObj);
        this.sendData.push(
          `绘制条码：${this.barcodeObj.x},${this.barcodeObj.y},${this.barcodeObj.codeType},${this.barcodeObj.height},${this.barcodeObj.displayBarCode},${this.barcodeObj.rotation},${this.barcodeObj.narrow},${this.barcodeObj.wide},${this.barcodeObj.alignment},${this.barcodeObj.content}`
        );
      } else if (this.printIndex === 4) {
        // 绘制二维码
        this.pelData.push(this.qrcodeObj);
        this.sendData.push(
          `绘制二维码：${this.qrcodeObj.x},${this.qrcodeObj.y},${this.qrcodeObj.eccLevel},${this.qrcodeObj.cellWidth},${this.qrcodeObj.encodeMode},${this.qrcodeObj.rotation},${this.qrcodeObj.codeMode},${this.qrcodeObj.mask},${this.qrcodeObj.content}`
        );
      } else if (this.printIndex === 5) {
        // 绘制图片
        if (Object.keys(this.imageRes).length === 0) {
          this.getImageData();
        }
        this.pelData.push(this.bitMapObj);
        this.sendData.push(
          `绘制图片：${this.bitMapObj.x},${this.bitMapObj.y},${this.bitMapObj.width},${this.bitMapObj.height}`
        );
      } else if (this.printIndex === 6) {
        // 绘制压缩图片
        if (Object.keys(this.imageRes).length === 0) {
          this.getImageData();
        }
        this.pelData.push(this.compressBitMapObj);
        this.sendData.push(
          `绘制压缩图片：${this.compressBitMapObj.x},${this.compressBitMapObj.y},${this.compressBitMapObj.width},${this.compressBitMapObj.height}`
        );
      }
      this.$refs.dialog1.close();
    },
    //清空数据
    clearData() {
      this.sendData = [];
      this.acceptData = [];
      this.pelData = [];
      CTPL.clearCache();
    },
    // 获取图片信息
    getImageData() {
      const $this = this;
      uni.getImageInfo({
        src: this.imagePath,
        success: (res) => {
          const scale = ($this.paperObj.width * 8) / res.width;
          const newWidth = $this.paperObj.width * 8;
          const newHeight = Math.ceil(res.height * scale);
          const ctx = uni.createCanvasContext("canvas", this);
          ctx.drawImage(this.imagePath, 0, 0, newWidth, newHeight);
          ctx.draw();
          uni.canvasGetImageData({
            canvasId: "canvas",
            x: 0,
            y: 0,
            width: $this.paperObj.width * 8,
            height: newHeight,
            success: function (response) {
              $this.imageRes = response;
            },
            fail: function (res) {
              console.log(res);
            },
          });
        },
      });
    },
    //打印
    print() {
      uni.showLoading();
      const $this = this;
      CTPL.setSize(this.paperObj.width, this.paperObj.height);
      CTPL.clearCache();
      this.pelData.forEach((value) => {
        if (value.type == "line") {
          CTPL.drawLine(value.x, value.y, value.width, value.height);
        } else if (value.type == "text") {
          CTPL.drawText(
            value.x,
            value.y,
            value.rotation,
            value.xRatio,
            value.yRatio,
            value.textAlignment,
            value.text
          );
        } else if (value.type == "barcode") {
          CTPL.drawBarCode(
            value.x,
            value.y,
            value.codeType,
            value.height,
            value.displayBarCode,
            value.rotation,
            value.narrow,
            value.wide,
            value.alignment,
            value.content
          );
        } else if (value.type == "qrcode") {
          CTPL.drawQRCode(
            value.x,
            value.y,
            value.eccLevel,
            value.cellWidth,
            value.encodeMode,
            value.rotation,
            value.codeMode,
            value.mask,
            value.content
          );
        } else if (value.type == "bitmap") {
          CTPL.drawBitMap(
            value.x,
            value.y,
            $this.imageRes.width,
            $this.imageRes.height,
            0,
            $this.imageRes.data
          );
        } else if (value.type == "compressbitmap") {
          CTPL.drawCompressBitMap(
            value.x,
            value.y,
            $this.imageRes.width,
            $this.imageRes.height,
            8,
            0,
            $this.imageRes.data
          );
        }
      });
      CTPL.setPrintCopies(1, 1);
      CTPL.execute();
      uni.hideLoading();
    },
  },
};
</script>

<style lang="scss">
.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  font-size: 28rpx;
}

.nav .ble {
  color: #1aad19;
}

.empty {
  padding: 10rpx 20rpx;
  text-align: right;
}
.text {
  display: block;
  height: 80rpx;
  line-height: 80rpx;
  text-indent: 1em;

  &.active {
    background: #e5e5e5;
  }
}

.box {
  height: 300rpx;
  background-color: #efefef;
}

.uni-collapse-item__title-text {
  font-weight: bold;
}

.item text {
  word-break: break-all;
}

.box .uni-section {
  background: #efefef !important;
}

.popup-cont {
  display: block;
  width: 100%;

  .popup-list {
    border: 1px solid #ebeef5;
    border-bottom: none;
    border-radius: 10rpx;

    input {
      display: flex;
      height: 60rpx;
      align-items: center;
      font-size: 24rpx;
      // line-height: 60rpx;
      border-bottom: 1px solid #ebeef5;
      padding-left: 15rpx;
      // border-radius: 10rpx;
    }
  }
}

.sel {
  background: green;
}

#canvas {
  position: absolute;
  top: -9999px;
}
</style>